package com.zlq.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zlq.mapper.UserMapper;
import com.zlq.pojo.User;
import com.zlq.service.impl.UserServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.List;


@Controller
public class UserController {
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserServiceImpl userService;
    /**
     * 分页展示
     * 保存在Model数据模型中
     */
    @RequestMapping("/list")
    public String listAll(@RequestParam(value = "pn",defaultValue = "1") Integer pn,Integer pageSize, Model model) {
        IPage<User> tPage = new Page<>(pn, 5);
        IPage<User> page = userMapper.selectPage(tPage, null);
        model.addAttribute("page",page);
        return "listUser";


    }

    /**
     * 携带数据去修改页面
     */
    @RequestMapping("/toUpdate")
    public String toUpdate(Long id, Model model) {
        try {
            User user = userService.selectById(id);
            model.addAttribute("user", user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "update";
    }

    /**
     * 修改后重定向到展示页面
     */
    @RequestMapping("/update")
    public String update(User user) {
        userService.updateById(user);
        return "redirect:/list?pn=1";
    }

    /**
     * 删除后重定向到展示页面
     */
    @RequestMapping("/delete")
    public String delete(Long id) {
        userService.delete(id);
        return "redirect:/list?pn=1";
    }

    /**
     * 添加完后重定向到展示页面
     */
    @RequestMapping("/insert")
    public String save(User user) {
        userService.save(user);
        return "redirect:/list?pn=1";
    }

    /**
     * 模糊查询
     */
    @RequestMapping("/search")
    public String search(String str, Model model) {
        List<User> us = userService.selectByLike(str);
        model.addAttribute("us", us);
        return "search";
    }
}
